package service

import (
	"fmt"
	"gitee.com/gomod/utils/logger"
	"learn-land-crawler/app/model"
	"math/rand"
	"strconv"
	"strings"
	"time"
)

func Save600XuePage() {
	total := Crawler600XueTotalPage()
	for i := 1; i <= total; i++ {
		p := Crawler600XuePage(i)
		Save600XuePageData(p)
		time.Sleep(1 * time.Second)
	}
}

func Save600XuePageData(arr []Xue600Page) {
	// 处理数据
	var cp model.CProduct
	for _, v := range arr {
		id, err := strconv.ParseUint(v.Id, 10, 64)
		if err != nil {
			logger.Error.Println(v, "，id 转换错误：", err)
			continue
		}
		p, _ := cp.FirstById(id)
		if p.ID == 0 {
			np := model.CProduct{
				Name:    v.Title,
				MainPic: v.Image,
			}
			id, err := strconv.ParseUint(v.Id, 10, 64)
			if err != nil {
				fmt.Println("转换错误：", err)
				return
			}
			np.ID = uint(id)
			t, err := time.Parse(time.RFC3339, v.Time)
			if err != nil {
				logger.Error.Println("日期转换出错: ", err)
			} else {
				np.UpdatedDay = &t
			}
			cp.Create(&np)
			categoryAndBrand(&np, v)
		} else {
			t, err := time.Parse(time.RFC3339, v.Time)
			if err != nil {
				logger.Error.Println("日期转换出错: ", err)
			} else {
				p.UpdatedDay = &t
			}
			p.Name = v.Title
			p.MainPic = v.Image
			cp.Update(p)
			categoryAndBrand(p, v)
		}
	}
}

func categoryAndBrand(np *model.CProduct, v Xue600Page) {
	var t model.Tag
	var pt model.ProductTag
	pt.DelAll(np.ID)
	for cs := range v.Categorys {
		b, _ := t.GetByCode(cs)
		if b.ID == 0 {
			b = &model.Tag{
				Code: cs,
				Name: v.Categorys[cs],
			}
			t.Create(b)
		}
		ptn := &model.ProductTag{
			ProductId: np.ID,
			TagId:     b.ID,
		}
		pt.Create(ptn)
	}
}

func Save600XudDetail(loginCookie []string) {
	var cp model.CProduct
	ids := cp.GetAll()
	size := 100
	total := len(ids)
	threads := total / size
	if total%size > 0 {
		threads++
	}
	for i := 0; i < threads; i++ {
		start := i * size
		end := (i + 1) * size
		if end > total {
			end = total
		}
		go doSave600XudDetail(ids[start:end], loginCookie)
	}
}

func doSave600XudDetail(ids []uint, loginCookie []string) {
	for _, id := range ids {
		d, err := Crawler600XueContentPrice(loginCookie, id)
		if err != nil {
			continue
		}
		Save600XueDetailData(d)
	}
}

func Save600XueDetailData(d Xue600Detail) {
	// 处理数据
	var cp model.CProduct
	id, err := strconv.ParseUint(d.Id, 10, 64)
	if err != nil {
		logger.Error.Println(d, "，id 转换错误：", err)
	}
	p, _ := cp.FirstById(id)
	p.Description = d.Content

	if d.Pwd != "" {
		p.Pwd = d.Pwd
	}
	sold, err := strconv.Atoi(d.Sold)
	if err == nil {
		p.Sold = uint16(sold)
	}

	commonPrice, err := strconv.ParseFloat(strings.ReplaceAll(d.Common, "钻", ""), 2)
	if err == nil {
		p.CommonPrice = uint16(commonPrice * 100)
	}

	memberPrice, err := strconv.ParseFloat(strings.ReplaceAll(d.Vip, "钻", ""), 2)
	if err == nil {
		p.MemberPrice = uint16(memberPrice * 100)
	}

	vipPrice, err := strconv.ParseFloat(strings.ReplaceAll(d.VipAll, "免费", ""), 2)
	if err == nil {
		p.VipPrice = uint16(vipPrice * 100)
	}
	cp.Update(p)
}

func Save600XudDownload(limit int) {
	logger.Info.Println("ready to Save600XudDownload")
	cookies, err := Login()
	for err != nil {
		cookies, err = Login()
	}
	DoSave600XudDownload(cookies, limit)

	ConverToTProduct(0)
}

func DoSave600XudDownload(cookies []string, limit int) {
	var cp model.CProduct
	pds, err := cp.GetNoDownloadUrl(limit)
	if err != nil {
		logger.Error.Println(err)
		return
	}
	i := 0
	for _, pd := range pds {
		d, err := Crawler600XueContentPrice(cookies, pd.ID)
		if err != nil {
			continue
		}
		pd.Pwd = d.Pwd
		xd, err := Crawler600XueDownload(cookies, pd.ID)
		if err != nil {
			continue
		}
		fmt.Println(xd)
		if xd.Url == "" {
			pd.DownloadUrl = "error"
		} else if xd.Url == "0" {
			i = limit
			logger.Error.Println("下载次数超出限制")
			break
		} else {
			// https://pan.baidu.com/s/1DMoS3cJUHjljoGpFta625w?pwd=1jz5
			splitStr := "pwd="
			if strings.Contains(xd.Url, "pwd=") {
				if strings.Contains(xd.Url, "&pwd=") {
					splitStr = "&pwd="
				} else if strings.Contains(xd.Url, "?pwd=") {
					splitStr = "?pwd="
				}
			}
			urls := strings.Split(xd.Url, splitStr)
			if len(urls) == 2 {
				pd.DownloadUrl = urls[0]
				pd.Pwd = urls[1]
				pd.DownloadType = 1
			} else {
				pd.DownloadUrl = xd.Url
				if pd.Pwd != "" {
					pd.DownloadType = 1
				} else {
					d, err = Crawler600XueContentPrice(cookies, pd.ID)
					if err != nil {
						continue
					}
					pd.Pwd = d.Pwd
					if pd.Pwd != "" {
						pd.DownloadType = 1
					}
				}
			}
		}
		i++
		n := time.Now()
		pd.PwdUpdatedDay = &n
		cp.Update(pd)
		time.Sleep(time.Duration((rand.Intn(21) + 40)) * time.Second)
	}
	if i < limit {
		DoSave600XudDownload(cookies, limit-i)
	}
}
